package org.grottarossa.ui.core.components.tables;

import org.grottarossa.template.data.pojo.table.Table;
import org.grottarossa.ui.core.ApplicationSession;
import org.grottarossa.ui.core.container.TableContainer;


import com.vaadin.data.Container;
import com.vaadin.data.Property;
import com.vaadin.ui.Field;
import com.vaadin.ui.TableFieldFactory;

/***
 * Tabella con filtri nell'header
 * @author 
 *
 */
public class TMSFilteredTable extends TMSTable
{
	/*** Container che gestisce i filtraggi ***/
	FilteredContainerWrapper m_container;
	private TMSTableFilterFieldFactory m_fieldsFactory;
	private final ApplicationSession m_appSession;

	public TMSFilteredTable(ApplicationSession appSession, Table data)
	{
		this.m_appSession = appSession;
		m_container = new FilteredContainerWrapper((TableContainer)createContainer(data));
		m_fieldsFactory = new TMSTableFilterFieldFactory(m_appSession, this);
		setTableFieldFactory(m_fieldsFactory);
		setEditable(true);
		setContainerDataSource(m_container);
		initTable(data);
		setSortDisabled(true);
	}

	/***
	 * Imposta il container. IMPORTANTE: Al momento sono suppertati solo i TableContainer
	 */
	@Override
	public void setContainerDataSource(Container container)
	{
		if(container instanceof FilteredContainerWrapper)
			m_container = (FilteredContainerWrapper)container;
		else if(container instanceof TableContainer)
			m_container = new FilteredContainerWrapper((TableContainer)container);

		super.setContainerDataSource(m_container);
	}

	/***
	 * Esegue il render di una cella. Da qui decido se mostrare il valore in caso di cella normale
	 * oppure mostrare il campo di filtraggio.
	 */
	@Override
	protected Object getPropertyValue(Object rowId, Object colId, Property property)
	{
        if (getTableFieldFactory() != null && m_container.getFilterItem() == rowId)
        {
            final Field f = getTableFieldFactory().createField(getContainerDataSource(),
                    rowId, colId, this);

            return f;
        }

        return formatPropertyValue(rowId, colId, property);
    }

	/***
	 * Imposta il tipo di campo filtro di una colonna come combo
	 * @param property Nome della property
	 */
	public void setFieldFilterTypeAsCombo(String property)
	{
		m_fieldsFactory.setFieldFilterTypeAsCombo(property);
	}
}
